<?php
/**
 * @author fw
 */
namespace traits;

use service\JsonService;
use think\Request;

use service\UploadService;

trait ShotcutControllerTrait
{
     /**
     * 设置单个产品状态（上下架）
     *
     * @return json
     */
    public function set_status($status = '', $id = '' , $field = 'status',$pk = 'id')
    {
        if ( $this->model == null ) {
            return JsonService::fail('模型未初始化');
        }

        if ($status == '' || $id == '') return JsonService::fail('缺少参数');

        $res = $this->model::where([$pk => $id])->update([$field => (int)$status]);
        if ($res !== false ) {
            return JsonService::successful($status == 1 ? '操作成功' : '操作成功');
        } else {
            return JsonService::fail($status == 1 ? '操作失败' : '操作失败');
        }
    }

    /**
     * 快速编辑
     *
     * @return json
     */
    public function set_value($field = '', $id = '', $value = '')
    {
        $field == '' || $id == '' || $value == '' && JsonService::fail('缺少参数');
        if ($this->model::where(['id' => $id])->update([$field => $value]))
            return JsonService::successful('保存成功');
        else
            return JsonService::fail('保存失败');
    }

    /**
     * 首页
     * @Author   FW
     * @DateTime 2021-01-13
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function index ()
    {
        $this->_index();
        return $this->fetch();
    }

    /**
     * 获取列表
     * @Author   FW
     * @DateTime 2021-01-13
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function get_list ()
    {
        $where = $this->request->get();
        $where['page']  = $where['page'] ?? 1;
        $where['limit'] = $where['limit'] ?? 20;
        return JsonService::successlayui($this->model::getList($where));
    }

    public function get_attr ($name , $trans = 1)
    {
        if ( isset($this->model::$$name) ) {
            $data = $this->model::$$name;
            if ( $trans == 1 ) {
                if ( is_array($data) ) {
                    $data = [];
                    foreach ( $this->model::$$name as $k => $v ) {
                        $data[] = [
                            'key' => $k,
                            'val' => $v
                        ];
                    }
                }
            }
            return JsonService::successful($data);
        }

         return JsonService::fail(sprintf('%s 属性不存在',$name));
    }

    /**
     * 获取所有数据
     * @Author   FW
     * @DateTime 2021-01-13
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function get_all ()
    {
        $where = $this->request->get();
        return JsonService::successful($this->model::getListArr($where));
    }

    /**
     * 新增、编辑
     * @Author   FW
     * @DateTime 2021-01-13
     * @Email    123763712@qq.com
     * @param    integer          $id [description]
     */
    public function add( $id = 0 )
    {
        $data = [];
        if ( $id ) {
            $data = $this->model::getOne($id);
        }

        $this->_add();
        $this->assign('data' , json_encode($data));
        return $this->fetch();
    }

    /**
     * view
     * @Author   FW
     * @DateTime 2021-04-13
     * @Email    123763712@qq.com
     * @param    integer          $id [description]
     */
    public function view( $id )
    {
        $data = $this->model::getOne($id);
        if ( !empty($data) ) {
            return json([
                'code' => 200,
                'msg'  => '',
                'data' => $data
            ]);
        }
        return json([
            'code' => 400,
            'msg'  => 'error'
        ]);
    }

    /**
     * 保存
     * @Author   FW
     * @DateTime 2021-01-13
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function save()
    {
        $data = $this->request->post();

        $this->model::beginTrans();

        try {
            ## 自定义保存数据的额外操作
            $data = $this->_save($data);

            if ( !empty($data) && is_array($data) ) {
                $data_id = 0;
                if ( isset($data['id']) && $data['id'] > 0 ) {
                    $res     = $this->model::update($data);
                    $data_id = $data['id'];
                }else {
                    $res     = $this->model::create($data);
                    $data_id = $this->model::getLastInsID();
                }

                $res = $this->model::afterSave($data_id , $data);

                if ( $res !== false ) {
                    $this->model::commitTrans();
                    return JsonService::successful('操作成功!');
                }
            }
        } catch (\Exception $e ) {
            $this->model::rollbackTrans();
            return JsonService::fail($e->getMessage());
        }

        $this->model::rollbackTrans();
        return JsonService::fail('操作失败');

    }

    /**
     * 删除
     * @Author   FW
     * @DateTime 2021-01-13
     * @Email    123763712@qq.com
     * @param    [type]           $id [description]
     * @return   [type]               [description]
     */
    public function delete($id , $uid = 0)
    {
        if( !$id && !$uid ) return JsonService::fail('数据不存在!');

        $this->model::beginTrans();
        try {
            $res = $this->_delete($id);
            if ( $res !== true ) throw new \Exception('删除失败1001');

            if ( $id > 0 ) {
                $res = $this->model::where('id' , $id);
            }
            ## 临时兼容用户表UID
            else if ( $uid > 0 ) {
                $res = $this->model::where('uid' , $uid);
            }
            if ( isset($this->model::$softDelete) && $this->model::$softDelete == true ) {
                $res->update(['is_del' => time()]);
            } else {
                $res->delete();
            }
            if ( $res === false ) throw new \Exception('删除失败1002');

            $this->model::commitTrans();
            return JsonService::successful('操作成功!');

        } catch (\Exception $e ) {
            $this->model::rollbackTrans();
            return JsonService::fail($e->getMessage());
        }

        $this->model::rollbackTrans();
        return JsonService::fail('删除失败,请稍候再试!');
    }

    /**
     * 列表页额外操作 如无留空
     * @Author   FW
     * @DateTime 2021-01-13
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    protected function _index()
    {
        //
    }

    /**
     * 新增额外操作 如无留空
     * @Author   FW
     * @DateTime 2021-01-13
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    protected function _add()
    {
        //
    }

    /**
     * 保存额外操作
     * @Author   FW
     * @DateTime 2021-01-13
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    protected function _save( array $data )
    {
        //
        return $data;
    }

    /**
     * 删除额外操作
     * @Author   FW
     * @DateTime 2021-01-13
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    protected function _delete(int $id )
    {
        //
        return true;
    }

} //Class End